<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>我的购物车</title>
    <!--引入vue、element-ui、axios；注意：vue要在element-ui之前-->
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.13/vue.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.14/index.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.js"></script>
    <script src="/js/axios.helper.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.14/theme-chalk/index.css" rel="stylesheet">
    <style>
        .el-row {
            margin-bottom: 20px;

        &
        :last-child {
            margin-bottom: 0;
        }

        }
        .el-col {
            border-radius: 4px;
        }

        .bg-purple-dark {
            background: #99a9bf;
        }

        .grid-content {
            border-radius: 4px;
            min-height: 36px;
            /* 设置水平、垂直居中 */
            display: flex;
            justify-content: center; /* 水平居中 */
            align-items: center; /* 垂直居中 */
        }
    </style>
</head>
<body>
<div id="app">
    <el-container>
        <el-header>
            <!--element官网：Layout 布局，通过基础的 24 分栏，迅速简便地创建布局。-->
            <!--第一行：头部-->
            <el-row>
                <el-col :span="24">
                    <div class="grid-content bg-purple-dark">
                        <el-link :href="'/index.html'">蜗牛学苑</el-link>
                    </div>
                </el-col>
            </el-row>
        </el-header>
        <el-main>
            <!--第二行：搜索-->
            <el-row>
                <!--左边: 搜索-->
                <el-col :span="12">
                    <el-form :inline="true" :model="condition" class="demo-form-inline">
                        <el-form-item label="请输入">
                            <el-input v-model="condition.keyword" placeholder="书名/作者/类型"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="queryBook">查询</el-button>
                        </el-form-item>
                    </el-form>
                </el-col>
                <!--右边: 个人中心-->
                <el-col :span="12">
                    <div style="text-align: right">
                            <span v-if="realName == ''">
                                <el-link type="info" :href="'/login.html'">登录</el-link>
                                <el-link type="info">注册</el-link>
                            </span>
                        <span v-else>
                                欢迎你，{{realName}}
                                <el-link type="info" @click="logout">退出系统</el-link>
                            </span>

                        <el-link type="info">个人中心</el-link>
                        <el-link type="info" :href="'/cart.html'">我的购物车</el-link>
                        <el-link type="info" :href="'/order.html'">我的订单</el-link>
                    </div>
                </el-col>
            </el-row>

            <!--第三行：面包屑 导航-->
            <el-row>
                <el-col :span="24">
                    <el-breadcrumb separator="/">
                        <!-- 从后台获取所有类别，v-for 遍历-->
                        <el-breadcrumb-item v-for="type in typeList">
                            <el-link
                                    type="info"
                                    :href="'/index/showBookList?typeId=' + type.id"
                                    style="color:gray;font-weight: normal">{{type.name}}
                            </el-link>
                        </el-breadcrumb-item>
                    </el-breadcrumb>
                </el-col>
            </el-row>

            <!--收获地址-->
            <el-row>
                <el-col :span="12">
                    收货地址：
                    <el-select v-model="addressId" placeholder="请选择收货地址" style="width: 600px">
                        <el-option
                                v-for="item in addresses"
                                :key="item.address"
                                :label="item.address"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-col>
                <el-col :span="12">
                    <el-button type="success" @click="showAddressDialog()">新增收货地址</el-button>
                </el-col>
            </el-row>

            <!--显示购买的商品的详细-->
            <el-row>
                <el-col :span="24">
                    <el-table :data="cartVo.cartItemVos" tooltip-effect="dark" style="width: 100%">
                        <el-table-column prop="name" label="商品名称"></el-table-column>
                        <el-table-column label="商品图片">
                            <template slot-scope="scope">
                                <el-image style="width: 100px; height: 100px" :src="scope.row.imgsrc"></el-image>
                            </template>
                        </el-table-column>
                        <el-table-column prop="price" label="商品单价"></el-table-column>
                        <el-table-column prop="buycount" label="购买数量"></el-table-column>
                        <el-table-column prop="sumPrice" label="小计"></el-table-column>
                    </el-table>
                </el-col>
            </el-row>
            <!--显示总价-->
            <el-row>
                <el-col :span="22">总价（元）：{{cartVo.totalPrice}}</el-col>
                <el-col :span="2"><el-button @click="submitOrder()">提交订单</el-button></el-col>
            </el-row>


        </el-main>
    </el-container>

    <!--新增收获地址弹出框-->
    <el-dialog title="新增收货地址" :visible.sync="dialogVisible" width="40%">
        <el-form label-width="80px" :model="address">
            <el-form-item label="省">
                <el-select v-model="address.province" placeholder="请选择省" @change="loadCities()">
                    <el-option
                            v-for="p in provinces"
                            :key="p.id"
                            :label="p.name"
                            :value="p.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="市">
                <el-select v-model="address.city" placeholder="请选择市" @change="loadAreas()">
                    <el-option
                            v-for="c in cities"
                            :key="c.id"
                            :label="c.name"
                            :value="c.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="区域">
                <el-select v-model="address.area" placeholder="请选择市">
                    <el-option
                            v-for="a in areas"
                            :key="a.id"
                            :label="a.name"
                            :value="a.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <!--还需要再加：详细地址，邮箱，收货人，联系电话-->
            <el-form-item label="详细地址">
                <el-input type="textarea" v-model="address.detailAddress"></el-input>
            </el-form-item>
            <el-form-item label="手机号码">
                <el-input v-model="address.tel"></el-input>
            </el-form-item>
            <el-form-item label="收件人">
                <el-input v-model="address.reciver"></el-input>
            </el-form-item>
            <el-form-item label="邮政编码">
                <el-input v-model="address.emailCode"></el-input>
            </el-form-item>
            <el-form-item label="默认地址">
                <el-radio-group v-model="address.isDefault">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addAddress()">确 定</el-button>
      </span>
    </el-dialog>

</div>
</body>
<script>
    new Vue({
        el: "#app",
        data() {
            return {
                // 搜索对象
                condition: {
                    keyword: ""
                },
                // 分类
                typeList: [],
                realName: '',
                addresses: [],
                addressId: 0,
                dialogVisible: false,
                address:{
                    provinces:'',
                    city:'',
                    area:''
                },
                provinces:[],
                cities:[],
                areas:[],
                cartVo: {
                    totalPrice: 0,
                    cartItemVos: []
                },
                orderNum:'',
                uniquecode: ''
            }
        },
        methods: {
            queryBook() {

            },
            // 查询图书分类
            queryBookType() {
                axios.get('/booktype').then(resp => {
                    console.log('booktype', resp)
                    this.typeList = resp.data.data;
                })
            },
            getCurrentUser() {
                axios.get('/user/getCurrentUser').then(resp => {
                    if (resp.data.data != null && resp.data.data != '') {
                        this.realName = resp.data.data;
                    } else {
                        this.realName = '';
                    }
                })
            },
            logout() {
                this.$confirm('此操作将要退出系统，是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    localStorage.removeItem("token");
                    location.href = "/index.html"
                });
            },
            // 异步请求后台，查询收获地址
            initAddressData() {
                axios.get('/address/findAll').then(resp => {
                    this.addresses = resp.data.data;
                    // 处理默认选中
                    this.addresses.forEach(address => {
                        if (address.isDefault == "1") {
                            this.addressId = address.id;
                        }
                    })
                    console.log("this.addresses:{}", this.addresses)
                })
            },
            // 新增收获地址弹出框
            showAddressDialog() {
                this.dialogVisible = true;
                // 查询所有的省份
                axios.get('/address/getAllProvinces').then(resp=>{
                    this.provinces = resp.data.data;
                })
            },
            // 选择省份发送变化，加载城市
            loadCities(){
                // 省份变化，先清空城市、区域
                this.address.city = '';
                this.address.area = '';

                // 根据省份，加载城市
                let provinceId = this.address.province;
                axios.get(`/address/getAllCities?proviceId=${provinceId}`).then(resp=>{
                    this.cities = resp.data.data;
                    console.log('this.cities:{}',this.cities)
                })
            },
            // 城市变化，加载区域
            loadAreas(){
                // 先清空区域
                this.address.area = ''

                // 根据城市，加载区域
                let city = this.address.city;
                axios.get(`/address/getAllAreas?cityId=${city}`).then(resp=>{
                    this.areas = resp.data.data;
                })
            },
            addAddress(){
                axios.post("/address/save",this.address).then(resp=>{
                    if (resp.data.code == 200) {
                        this.$message.success('添加地址成功');
                        this.initAddressData();
                    } else {
                        this.$message.error(resp.data.message);
                    }
                })
            },
            initCalcItem(){
                // 从cart.html购物车页面选中结算项，来到calc.html页面传入的图书id
                let ids = [[${ids}]];
                axios.post('/cart/calc',ids).then(resp=>{
                    this.cartVo.totalPrice = resp.data.data.totalPrice;
                    this.cartVo.cartItemVos = resp.data.data.cartItemVos;
                })
            },
            // 提交订单
            submitOrder(){
                // 请求头中携带唯一标记访问后台
                axios.post(`/order/submitOrder/${this.addressId}/${this.orderNum}`,this.cartVo,{
                    headers: {
                        "uniquecode": this.uniquecode
                    }
                }).then(resp=>{
                    if (resp.data.code == 200) {
                        this.$message.success("提交订单成功！");
                        // 提交成功，3秒后跳转
                        setTimeout(()=>{
                            location.href = '/order.html'
                        },3000)
                    } else {
                        this.$message.error(resp.data.message);
                    }
                })
            }
        },
        created() {
            this.queryBookType();
            this.getCurrentUser();
            this.initAddressData();
            this.initCalcItem(); // 查询结算购物项（从购物车中查询数据返回）
            this.orderNum = "WNGZ" + Date.now();
            // 访问幂等接口的请求头中携带一个唯一标记；用于幂等校验。
            this.uniquecode = "UNIQUECODE" + Date.now();
        }
    })
</script>
</html>